<template>
  <div>
    <!-- Breadcrumb 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>科室管理</el-breadcrumb-item>
      <el-breadcrumb-item>科室列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 功能按钮 -->
    <el-row :gutter="20">
      <el-col :span="3" :offset="6">
        <el-button type="primary" icon="el-icon-circle-plus" @click="depDialogVisible = true">新增科室</el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="danger" icon="el-icon-delete-solid" @click="removeBatch(sels)">批量删除</el-button>
      </el-col>
      <el-col :span="3">
        <el-upload
          class="filter-item"
          name="excelFile"
          :action="uploadUrl()"
          :on-error="uploadFalse"
          :on-success="uploadSuccess"
          :before-upload="beforeAvatarUpload"
          :limit="1"
          accept=".xlsx, .xls"
          :show-file-list="false"
          :file-list="fileList"
          ref="upload"
        >
          <el-button style="margin-left: 10px;" icon="el-icon-edit" type="primary">导入科室</el-button>
        </el-upload>
      </el-col>
      <el-col :span="3">
        <el-button @click="downloadDemo" type="info" icon="el-icon-download">下载模板</el-button>
      </el-col>
    </el-row>

    <!-- 条件搜索栏 -->
    <el-form
      ref="searchFormRef"
      :model="queryForm"
      label-width="40px"
      label-position="top"
      :inline="true"
      class="demo-form-inline"
    >
      <el-form-item label="科室编码">
        <el-input placeholder="请填写科室编码" v-model="queryForm.deptcode" clearable></el-input>
      </el-form-item>
      <el-form-item label="科室名称">
        <el-input placeholder="请填写科室名称" v-model="queryForm.deptname" clearable></el-input>
      </el-form-item>
      <el-form-item label="科室分类">
        <el-select v-model="queryForm.deptcategoryid">
          <el-option label="空" value></el-option>
          <el-option
            v-for="item in options1"
            :key="item.id"
            :label="item.constantname"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="科室类型">
        <el-select v-model="queryForm.depttype">
          <el-option label="空" value></el-option>
          <el-option
            v-for="item in options2"
            :key="item.depttype"
            :label="item.label"
            :value="item.depttype"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-top:50px;margin-left:20px">
        <el-button type="success" @click="queryDept">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- card展示 -->
    <el-card>
      <el-table @selection-change="selsChange" :data="departList" border stripe>
        <!-- 为表格添加一个编号（索引） -->
        <el-table-column type="selection" width="65"></el-table-column>
        <el-table-column type="index" label="编号"></el-table-column>
        <el-table-column prop="deptcode" label="科室编码"></el-table-column>
        <el-table-column prop="deptname" label="科室名称"></el-table-column>
        <el-table-column prop="constantitem.constantname" label="科室分类"></el-table-column>
        <el-table-column prop="depttype" label="科室类型" :formatter="formatType"></el-table-column>
        <el-table-column width="200px" label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除信息" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeDepById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- Pagination分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加信息弹出框 -->
    <el-dialog title="添加科室信息" :visible.sync="depDialogVisible" width="50%">
      <!-- 创建一个添加科室表单 -->
      <!-- 写完表单后要添加数据绑定以及检验的规则 -->
      <el-form :model="depForm" :rules="depFormRules" ref="depFormRef">
        <el-form-item prop="deptcode" label="科室编码">
          <el-input
            v-model="depForm.deptcode"
            prefix-icon="iconfont icon-user"
            placeholder="请填写科室编码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="deptname" label="科室名称">
          <el-input
            v-model="depForm.deptname"
            prefix-icon="iconfont icon-user"
            placeholder="请填写科室名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="deptcategoryid" label="科室分类">
          <el-select v-model="depForm.deptcategoryid" placeholder="请选择科室分类">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.constantname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="depttype" label="科室类型">
          <el-select v-model="depForm.depttype" placeholder="请选择科室类型">
            <el-option
              v-for="item in options2"
              :key="item.depttype"
              :label="item.label"
              :value="item.depttype"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="depDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹出框 -->
    <el-dialog title="修改科室信息" :visible.sync="updateDialogVisible" width="50%">
      <!-- 创建一个表单 -->
      <!-- 写完表单后要修改数据绑定以及检验的规则 -->
      <el-form :model="updateForm" :rules="updateFormRules" ref="updateFormRef">
        <el-form-item prop="deptcode" label="科室编码">
          <el-input
            v-model="updateForm.deptcode"
            prefix-icon="iconfont icon-user"
            placeholder="请填科室编码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="deptname" label="科室名称">
          <el-input
            v-model="updateForm.deptname"
            prefix-icon="iconfont icon-user"
            placeholder="请输科室名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="deptcategoryid" label="科室分类">
          <el-select v-model="updateForm.deptcategoryid" placeholder="请选择科室分类">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.constantname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="depttype" label="科室类型">
          <el-select v-model="updateForm.depttype" placeholder="请选择科室类型">
            <el-option
              v-for="item in options2"
              :key="item.depttype"
              :label="item.label"
              :value="item.depttype"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="sureUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //列表显示条目总数
      total: 0,
      //初始化分页信息
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      //常数项分类类别
      itemInfo: {
        constanttypeid: "1",
      },
      //科室列表信息
      departList: [],
      sels: [],
      //科室分类选择器
      options1: [],
      //科室类型选择器
      options2: [
        {
          depttype: "1",
          label: "临床",
        },
        {
          depttype: "2",
          label: "医技",
        },
        {
          depttype: "3",
          label: "财务",
        },
        {
          depttype: "4",
          label: "行政",
        },
        {
          depttype: "5",
          label: "其他",
        },
      ],

      //科室添加Dilog框默认为关闭
      depDialogVisible: false,
      //修改查询Dilog框默认关闭
      updateDialogVisible: false,
      //添加信息表单
      depForm: {
        deptcode: "",
        deptname: "",
        deptcategoryid: null,
        depttype: null,
      },
      //查询表单信息
      queryForm: {
        deptcode: "",
        deptname: "",
        deptcategoryid: "",
        depttype: "",
        pageNum: "1",
        pageSize: "5",
      },
      //修改表单信息
      updateForm: {
        id: "",
        deptcode: "",
        deptname: "",
        deptcategoryid: 0,
        depttype: "",
      },
      fileList: [],
      //添加信息表单验证
      depFormRules: {
        deptcode: [
          { required: true, message: "科室编码不能为空", trigger: "blur" },
        ],
        deptname: [
          { required: true, message: "科室名称不能为空", trigger: "blur" },
        ],
        deptcategoryid: [
          {
            required: true,
            message: "科室分类不能为空",
            trigger: ["blur", "change"],
          },
        ],
        depttype: [
          {
            required: true,
            message: "科室类型不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      //修改信息表单验证
      updateFormRules: {
        deptcode: [{ required: true, message: "不能为空", trigger: "blur" }],
        deptname: [{ required: true, message: "请输入密码", trigger: "blur" }],
        deptcategoryid: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        depttype: [
          {
            required: true,
            message: "不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    //初始化列表查询
    this.getDeprtList();
    //初始化科室分类选择器
    this.getItem();
  },
  methods: {
    //科室类型字段格式化
    formatType: function (row, column) {
      if (row.depttype == "1") {
        return "临床";
      } else if (row.depttype == "2") {
        return "医技";
      } else if (row.depttype == "3") {
        return "财务";
      } else if (row.depttype == "4") {
        return "行政";
      } else {
        return "其他";
      }
    },
    //查询所有科室列表
    async getDeprtList() {
      const { data: res } = await this.$http.get(`department/queryDeptName`, {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取科室信息失败");
      }
      this.departList = res.list;
      this.total = res.total;
      console.log(res);
    },
    //查询所有科室分类
    async getItem() {
      const { data: res } = await this.$http.get(`department/queryItem`, {
        params: this.itemInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取科室分类信息失败");
      }
      this.options1 = res.list;
      console.log(res);
    },

    //添加科室信息
    async sureAdd() {
      this.$refs.depFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }

        const { data: res } = await this.$http.post(
          `department/insertDept`,
          this.depForm
        );
        if (res.meta.status !== 200) {
          return this.$message.error("添加科室信息失败");
          console.log(res.meta.status);
        }
        this.$refs.depFormRef.resetFields();
        this.depDialogVisible = false;
        this.getDeprtList();
      });
    },

    //分页按钮功能
    handleSizeChange(size) {
      if (
        this.queryForm.deptname != "" ||
        this.queryForm.deptcode != "" ||
        this.queryForm.deptcategoryid != "" ||
        this.queryForm.depttype != ""
      ) {
        this.queryForm.pageSize = String(size);
        this.queryDept();
      } else {
        this.queryInfo.pageSize = size;
        this.getDeprtList();
      }
    },
    handleCurrentChange(page) {
      if (
        this.queryForm.deptname != "" ||
        this.queryForm.deptcode != "" ||
        this.queryForm.deptcategoryid != "" ||
        this.queryForm.depttype != ""
      ) {
        this.queryForm.pageNum = String(page);
        this.queryDept();
      } else {
        this.queryInfo.pageNum = page;
        this.getDeprtList();
      }
    },

    //根据id删除科室信息
    async removeDepById(row) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.get(`department/deleteDepById`, {
        params: { id: row },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("删除科室信息失败");
      }
      this.getDeprtList();
    },

    //根据条件查询科室信息
    async queryDept() {
      const { data: res } = await this.$http.post(
        "department/queryDept",
        this.queryForm
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取科室信息失败");
      }
      this.departList = res.department;
      this.total = res.total;
      this.$refs.searchFormRef.resetFields();
      console.log(res);
    },

    //批量删除
    async removeBatch(rows) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      var ids = [];
      rows.forEach((element) => {
        ids.push(element.id);
      });
      //发送删除请求
      const { data: res } = await this.$http.post(`department/deleteByChoose`, {
        info: ids,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("删除科室信息失败");
      }
      this.getDeprtList();
    },

    //批量删除 将复选框选中id放进数组
    selsChange(sels) {
      this.sels = sels;
    },
    //修改对话框数据回显
    async showEditDialog(row) {
      this.updateDialogVisible = true;
      //根据id获取用户信息
      const { data: res } = await this.$http.get(`department/selectDeptById`, {
        params: { id: row },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("根据id科室信息失败");
      }
      console.log(res);
      this.updateForm.deptcode = String(res.department.deptcode);
      this.updateForm.deptname = String(res.department.deptname);
      this.updateForm.deptcategoryid = res.department.deptcategoryid;
      this.updateForm.depttype = String(res.department.depttype);
      this.updateForm.id = String(row);
    },

    //确定修改科室信息
    async sureUpdate() {
      this.$refs.updateFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }

        const { data: res } = await this.$http.post(
          `department/updateDept`,
          this.updateForm
        );
        if (res.meta.status != 200) {
          return this.$message.error("修改科室信息失败");
        }
        this.$refs.updateFormRef.resetFields();
        this.getDeprtList();
        this.updateDialogVisible = false;
      });
    },

    uploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.meta.status == 200) {
        this.$message({
          message: "批量添加成功！",
          type: "success",
        });
        this.getDeprtList();
        this.$refs.upload.clearFiles();
      } else {
        this.$message({
          message: "批量添加失败！",
          type: "error",
        });
      }
    },
    uploadFalse(response, file, fileList) {
      this.$message({
        message: "文件上传失败！",
        type: "error",
      });
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message({
          message: "上传模板只能是 xls、xlsx格式!",
          type: "error",
        });
      }
      if (!isLt2M) {
        console.log("上传模板大小不能超过 10MB!");
        this.$message({
          message: "上传模板大小不能超过 10MB!",
          type: "error",
        });
      }
      return extension || extension2 || extension3 || (extension4 && isLt2M);
    },
    uploadUrl: function () {
      return "http://localhost:8085/his/department/ExcelInsertDept";
    },

    downloadDemo() {
      let url = "/department/downloadExcel";
      let thistime = new Date();
      let suftime = thistime.getTime();
      this.exportData(url, null, "数据模板_" + suftime);
    },

    exportData(url, data, fileName) {
      this.$http({
        method: "POST",
        url: url,
        data: data,
        responseType: "blob",
      })
        .then((response) => {
          if (!response) {
            return;
          }
          const blob = new Blob([response.data]);
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            let u = window.URL.createObjectURL(response.data);
            let aLink = document.createElement("a");
            aLink.style.display = "none";
            aLink.href = u;
            aLink.setAttribute("download", fileName + ".xlsx");
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
            window.URL.revokeObjectURL(u);
          }
        })
        .catch((error) => {
          throw error;
        });
    },
  },
};
</script>

<style lang="less" scoped></style>
